package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

type Data struct {
	id    int
	name string
}

var slice []Data

//golang操作mysql实现curd基础操作
func main() {
	db, error := sql.Open("mysql", "root:123456@tcp(192.168.79.206:3306)/test?charset=utf8")
	if error != nil {
		log.Fatal(error)
	}
	//select
	rows, error := db.Query("SELECT * FROM user")
	if error!=nil{
		fmt.Println("query error",error)
		return
	}
	for rows.Next() {
		var rid int
		var reward string
		error = rows.Scan(&rid, &reward)
		a := Data{rid, reward}
		slice = append(slice, a)
	}

	fmt.Println(slice)
	for _, v := range slice {
		fmt.Println(v)
	}

	//update
	update, error := db.Prepare("UPDATE user SET name =? WHERE id = ?")
	res, _ := update.Exec("tiger", 1)
	id, error := res.RowsAffected()
	fmt.Println(id)

	//insert
	insert, error := db.Prepare("INSERT into user (`name`) values ( ?)")
	insetRes, _ := insert.Exec("Docker")
	fmt.Println(insetRes)
	insertId, _ := insetRes.LastInsertId()
	fmt.Println(insertId)

	//delete
	delete, error := db.Prepare("DELETE FROM user WHERE id = ?")
	deleteRes, _ := delete.Exec(10)
	fmt.Println(deleteRes)
}
